namespace RBAC.Write.Api.Application.Handler.BomHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.BomCommand;

    /// <summary>
    /// 逻辑删除 BOM 明细 处理器
    /// </summary>
    public class BomItemDeleteHandler : IRequestHandler<BomItemDeleteCommand, APIResult<int>>
    {
        private readonly IBaseRepository<BomItem> _bomItemRepo;
        private readonly ILogger<BomItemDeleteHandler> _logger;

        public BomItemDeleteHandler(
            IBaseRepository<BomItem> bomItemRepo,
            ILogger<BomItemDeleteHandler> logger)
        {
            _bomItemRepo = bomItemRepo;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(BomItemDeleteCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (!request.Id.HasValue)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "请提供要删除的明细Id", Data = 0 });

                int affected = 0;
                // 单个根节点：递归级联逻辑删除
                var exists = _bomItemRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.Id.Value });
                if (exists == null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "BOM明细不存在", Data = 0 });

                var sqlCte = @"
WITH cte AS (
    SELECT Id FROM BomItem WHERE Id = @RootId AND IsDeleted = 0
    UNION ALL
    SELECT bi.Id FROM BomItem bi INNER JOIN cte ON bi.ParentId = cte.Id WHERE bi.IsDeleted = 0
)
UPDATE BomItem SET IsDeleted = 1 WHERE Id IN (SELECT Id FROM cte);
";
                affected = _bomItemRepo.Execute(sqlCte, new { RootId = request.Id.Value });

                result.Code = affected > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = affected > 0 ? "删除BOM明细成功（级联删除子节点）" : "删除BOM明细失败";
                result.Data = affected;
            }
            catch (OperationCanceledException)
            {
                _logger?.LogWarning("删除BOM明细被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "删除BOM明细异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "删除BOM明细异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
